package com.salton123.lib_database.db.repo

import android.content.pm.ApplicationInfo
import androidx.lifecycle.MutableLiveData
import com.salton123.app.BaseApplication
import com.salton123.lib_database.RehaDatabase
import com.salton123.lib_database.db.dao.ApkDao
import com.salton123.lib_database.db.entity.ApkEntity
import com.salton123.log.XLog

/**
 * Time:5/9/21 11:13 PM
 * Author:
 * Description:
 */
object ApkRepository : ApkDao by RehaDatabase.Impl.apkDao() {
    private const val TAG = "ApkRepository"
    val packageManager = BaseApplication.sInstance.packageManager
    private val apkListRet = MutableLiveData<MutableList<ApkEntity>>()
    fun loadApkList(): MutableLiveData<MutableList<ApkEntity>> {
        val apkEntities = packageManager.getInstalledPackages(0).filter { !isSystemApp(it.applicationInfo) }.map {
            ApkEntity(it.packageName, it.applicationInfo.loadLabel(packageManager).toString(),
                it.applicationInfo.sourceDir, it.applicationInfo.publicSourceDir, it.versionName)
        }
        XLog.i(TAG, "loadApkList:${apkEntities.size}")
        apkListRet.postValue(apkEntities.toMutableList())
        return apkListRet
    }

    private fun isSystemApp(applicationInfo: ApplicationInfo): Boolean {
        return applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
    }
}